<template>
  <div class="start-avatar vertical">
    <el-avatar
        :icon="icon"
        :size="size"
        :shape="shape"
        :src="modelValue"
        @click="previewAvatar">
    </el-avatar>

    <div class="margin-top">
      <el-upload ref="upload"
                 :action="action"
                 v-model="avatarModel"
                 :limit="1"
                 :onExceed="onExceed"
                 :before-upload="beforeUpload"
                 :http-request="updateFile"
                 :on-success="uploadSuccess"
                 :show-file-list="false"
                 accept="image/*">
        <template #trigger>
          <el-button text type="primary">上传头像</el-button>
        </template>
      </el-upload>
    </div>
  </div>


</template>
<script>
import {getUploadConfig} from "@/config/env";
import {genFileId} from "element-plus";
import {getAsVal} from "components/avue/utils/util";
import {DIC_HTTP_PROPS} from "components/avue/global/variable";

const tempConfig = getUploadConfig();
export default {
  name: "startAvatar",
  computed: {
    updatePropsHttp() {
      return Object.assign({}, tempConfig.propsHttp, this.propsHttp)
    },
  },
  props: {
    action: {
      type: String,
      default: () => {
        return tempConfig.action
      }
    },
    propsHttp: {
      type: Object,
      default: () => {
        return Object.assign(DIC_HTTP_PROPS, tempConfig.propsHttp)
      }
    },
    shape: {
      type: String,
    },
    size: {
      type: String,
    },
    fileSize: {
      type: Number,
      default: null
    },
    icon: {
      type: String,
    },

    modelValue: {
      type: [String, Array],
      default: null,
    },

  },
  data() {
    return {
      avatarModel: this.modelValue,
    }
  },
  methods: {
    previewAvatar() {
      if (!this.modelValue || this.modelValue.length < 1) {
        return
      }
      let images = this.modelValue.map(e => {
        let result = {}
        result.url = e
        return result
      })

      this.$ImagePreview(images)
    },
    onExceed(files) {
      this.$refs.upload.clearFiles();
      const file = files[0]
      file.uid = genFileId()
      this.$refs.upload.handleStart(file)
    },
    beforeUpload(rawFile) {
      if (this.fileSize === null || this.fileSize === undefined || this.fileSize < 0) {
        return true;
      }
      let fileSizeKB = rawFile.size / 1024
      this.$message.error("文件太大了，请上传小于" + this.formatFileSize(this.fileSize * 1024) + "的文件")
      return fileSizeKB <= this.fileSize;
    },
    updateFile(val) {
      let param = new FormData();
      param.append(this.updatePropsHttp.fileName, val.file);
      return this.$axios.post(val.action, param)
    },
    uploadSuccess(response, uploadFile, uploadFiles) {
      let res = getAsVal(response.data, this.updatePropsHttp.res);
      let url = getAsVal(res, this.updatePropsHttp.url)
      this.$emit("update:modelValue", [url])
      this.$refs.upload.clearFiles()
    },
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
    }
  }
}
</script>
<style lang="scss" scoped>
@import "start-avatar";
</style>